package com.gxa.goods.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gxa.goods.mapper.TemplateMapper;
import com.gxa.goods.service.TemplateService;
import com.gxa.luckin.core.exception.BusinessException;
import com.gxa.luckin.core.exception.MessageCode;
import com.gxa.luckin.core.pojo.Template;
import com.gxa.luckin.core.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service("templateService")
public class TemplateServiceImpl implements TemplateService {

    @Resource
    private TemplateMapper templateMapper;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    //确定redis中的前缀
    private static final String TEMPLATE_ONE="template:";

    // 指定过期时间常量
    private static final Integer TEMPLATE_CACHE_EXPIRE=2;
    /**
     * 查询全部列表
     * @return
     */
    @Override
    public List<Template> findAll() {
        //全查询
        return templateMapper.selectAll();
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @Override
    public Template findById(Integer id){
        //先从缓存中查
        BoundValueOperations<String, Object> sso = redisTemplate.boundValueOps(TEMPLATE_ONE + id);
        final Object o = sso.get();//如果有就是json格式的信息
        //判断是否是空
        final boolean empty = StringUtils.isEmpty(o);
        if (empty){
             Template template2 = templateMapper.selectByPrimaryKey(id);//查到缓存到redis
            if (template2==null){
                sso.set("null",30,TimeUnit.SECONDS);//防止数据穿透
            }
            //将商品对象转换为json
            final String s = JsonUtils.objectToJson(template2);
            //设置过期时间，防止雪崩
            sso.set(s,TEMPLATE_CACHE_EXPIRE, TimeUnit.HOURS);
            return template2;
        }
        return  JsonUtils.jsonToObject(o.toString(), Template.class);
    }


    /**
     * 增加
     * @param template
     */
    @Override
    public void add(Template template){
        templateMapper.insert(template);
    }


    /**
     * 修改
     * @param template
     */
    @Override
    public void update(Template template){
        templateMapper.updateByPrimaryKey(template);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(Integer id){
        //先删除缓存
        redisTemplate.delete(TEMPLATE_ONE + id);
        templateMapper.deleteByPrimaryKey(id);
    }


    /**
     * 条件查询
     * @param searchMap
     * @return
     */
    @Override
    public List<Template> findList(Map<String, Object> searchMap){
        Example example = createExample(searchMap);
        return templateMapper.selectByExample(example);
    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Template> findPage(int page, int size){
        PageHelper.startPage(page,size);
        return (Page<Template>)templateMapper.selectAll();
    }

    /**
     * 条件+分页查询
     * @param searchMap 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public Page<Template> findPage(Map<String,Object> searchMap, int page, int size){
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        return (Page<Template>)templateMapper.selectByExample(example);
    }

    @Override
    public Boolean removeTemplateCache(Long id) throws BusinessException {
        Boolean delete = redisTemplate.delete(TEMPLATE_ONE + id);
        if(!delete){
            throw new BusinessException(MessageCode.BANNER_INDEX_QUANTITY);
        }
        return delete;
    }

    /**
     * 构建查询对象
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Template.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 模板名称
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                criteria.andLike("name","%"+searchMap.get("name")+"%");
           	}

            // ID
            if(searchMap.get("id")!=null ){
                criteria.andEqualTo("id",searchMap.get("id"));
            }
            // 规格数量
            if(searchMap.get("specNum")!=null ){
                criteria.andEqualTo("specNum",searchMap.get("specNum"));
            }
            // 参数数量
            if(searchMap.get("paraNum")!=null ){
                criteria.andEqualTo("paraNum",searchMap.get("paraNum"));
            }

        }
        return example;
    }

}
